<?php
/**
 * Created by gby.
 * User: Administrator
 * Date: 2018/7/31
 * Time: 15:45
 */

namespace Admin\Frontend\Controllers;

use Admin\Models\school\XhschoolApply;
use Admin\Models\school\XhschoolApplyLog;
use Admin\Models\school\XhschoolInfo;
use Exception;
use Helpers\Hrm;
use Helpers\Main;
use Helpers\Assets;
use Helpers\Template;
use Helpers\Tool;
use Helpers\User;
use Modules\Power;
use Modules\School;
use Modules\Stud;
use Phalcon\Mvc\View;
use Admin\Models\user\XhsysUser;
use Admin\Models\crm\XhcustContact;
use Admin\Models\crm\XhcustInfo;
use stdClass;
use Admin\Models\hrm\XhhrmDepart;

class SchoolApplyController extends ControllerBase
{
    private static $applyStatus = [
        1 => '待市场部审批',
        2 => '待运营部审批',
        3 => '待财务部审批',
        4 => '审批通过',
        5 => '市场部审批不通过',
        6 => '运营部审批不通过',
        7 => '财务部审批不通过',
    ];

    private static $depToStatus = [
        'XHSCB' => [1, 2, 3, 4, 5, 6, 7],//市场部
        'XHYYB' => [2, 3, 4, 6, 7],//运营
        'XHCWB' => [3, 4, 5, 7],//财务
    ];

    private static $applyType = [
        1 => '教师子女',
        2 => '贫困生',
        3 => '重新购买',
        4 => '缴费凭证丢失',
        5 => '学校领导',
        6 => '领导子女',
        7 => '平板发放',
        8 => '校外领导',
        9 => '新增学生',
        10 => '平板租用',
    ];

    private static $typeExpansion = [
        1 => [
            2 => '收费教师子女',
            3 => '免费教师子女'
        ],
        2 => [
            1 => '一级贫困生(收取服务费)',
            2 => '二级贫困生(不收取服务费)'
        ]
    ];
    private static $payState = [
        1 => '缴费未确认',
        2 => '未缴费',
    ];

    /**
     * 申请列表页面
     *
     * @return View|string
     *
     * create by gby 20180718
     * modify by zqk 20180926
     */
    public function studentApplyListAction()
    {
        if (!Power::exist('School_SpecialApplyList')) {
            return $this->sendViewError('无特殊申请权限');
        }
        Assets::easyUI('js/school_apply/studentApplyList.js');
        Assets::importMainJs('assets/easyui/datagrid-detailview.js');
        Assets::select2();
        Assets::sweetAlert2();
        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::importJs('../customer/js/myMain.js');
        Assets::viewer();
        $this->view->pick('school_apply/studentApplyList');
        Main::showNavPosition();
        $listSearchArr = $listButtonArr = $formButtonArr = [];
        $power = [];
        if (Power::exist('School_SpecialApplyList_Add')) {
            $listButtonArr[] = [
                'id' => 'bt_list_apply',
                'class' => 'menubutton',
                'text' => '申请',
                'plain' => 'true',
                'icon' => 'fa-pencil',
                'style' => 'cursor: pointer;'
            ];
            $power['apply'] = 1;
        }
        if (Power::exist('School_SpecialApplyList_Check')) {
            $listButtonArr[] = [
                'id' => 'bt_list_check',
                'class' => 'menubutton',
                'text' => '审批',
                'plan' => 'true',
                'icon' => 'fa-check',
                'style' => 'margin-left:10px;cursor: pointer;'
            ];
            $power['check'] = 1;
        }
        if (Power::exist('School_SpecialApplyList_Del')) {
            $listButtonArr[] = [
                'plain' => 'true',
                'id' => 'bt_list_del',
                'text' => '删除',
                'icon' => 'fa-trash',
                'style' => 'margin-left:10px'
            ];
            $power['delete'] = 1;
        }
        if (Power::exist('School_SpecialApplyList_Edit')) {
            $listButtonArr[] = [
                'plain' => 'true',
                'id' => 'bt_list_edit',
                'text' => '编辑',
                'icon' => 'fa-edit',
                'style' => 'margin-left:10px'
            ];
            $power['edit'] = 1;
        }
        $listButtonArr[] = [
            'plain' => 'true',
            'id' => 'bt_list_pack',
            'text' => '一键收起',
            'icon' => 'fa-compress',
            'style' => 'margin-left:10px'
        ];
        $listButtonArr[] = [
            'plain' => 'true',
            'id' => 'bt_list_expand',
            'text' => '一键展开',
            'icon' => 'fa-expand',
            'style' => 'margin-left:10px'
        ];
        $listButtonArr[] = [
            'plain' => 'true',
            'id' => 'bt_list_log',
            'text' => '审批记录',
            'icon' => 'fa-eye',
            'style' => 'margin-left:10px'
        ];
        if (Power::exist('School_SpecialApplyList_Add') && Power::exist('School_SpecialApplyList_Check')) {
            $listButtonArr[] = [
                'id' => 'bt_list_bEstablished',
                'class' => 'menubutton',
                'text' => '添加已审核',
                'plain' => 'true',
                'icon' => 'fa-plus',
                'style' => 'cursor: pointer;margin-left:10px'
            ];
            $power['bEstablished'] = 1;
        }

        if (Power::exist('School_SpecialApplyList_ApplyFor')) {
            $listButtonArr[] = [
                'plain' => 'true',
                'id' => 'bt_list_applyFor',
                'text' => '学生机申领',
                'icon' => 'fa-tablet',
                'style' => 'margin-left:10px'
            ];
            $power['applyFor'] = 1;
        }

        //搜索
        $listSearchArr[] = [
            'type' => 'select',
            'id' => 'list_type',
            'style' => 'width: 100px;',
            'data' => ['' => '--申请类型--'] + self::$applyType];
        $listSearchArr[] = ['type' => 'select',
            'label' => ' ',
            'id' => 'list_status',
            'style' => 'width: 120px;',
            'data' => ['' => '--状态--'] + self::$applyStatus];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： '];
        $listSearchArr[] = [
            'type' => 'button',
            'id' => 'bt_list_search',
            'text' => '查找',
            'icon' => 'fa-search',
            'style' => 'margin-left:10px'
        ];
        return $this->view->setVars([
            'List' => Template::createList('list', 'School_StudentApply', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'power' => $power,
        ]);
    }

    /**
     * 获取申请表的数据
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Helpers\XhException
     *
     * create by zqk 20181023
     * modify by zqk 20180926
     * modify by zqk 20181023
     */
    public function getApplyAction()
    {
        if (!Power::exist('School_SpecialApplyList')) {
            return $this->sendErrorResponse(403, '无特殊申请权限');
        }
        $key = trim($this->request->getPost('key', 'string'));
        $type = $this->request->getPost('type', 'int');
        $status = $this->request->getPost('status', 'int');
        $depTag = Main::getLoginUserInfo('depTag');
        $userId = Main::getLoginUserInfo('userId');
        $deps = User::getextrapower('dep', 'specialApply');  //获取扩展部门权限
        $schoolIds = School::getPower();
        $uids = [];
        $depTags = [];

        //根据扩展部门获取部门下的uid 以及部门 Tag
        if ($deps) {
            $uids = Hrm::getDepUserIdByDepId($deps);
            $depTags = $this->modelsManager->createBuilder()
                ->columns("sTag")
                ->addFrom('Admin\Models\hrm\XhhrmDepart')
                ->where('bDelete = 0')
                ->inwhere('iDepId', $deps)
                ->getQuery()
                ->execute()
                ->toArray();
            $depTags = array_column($depTags, 'sTag');
        }
        array_push($uids, $userId);
        $uids = array_unique($uids);
        //根据部门Tag获取对应的
        $depToStatus = self::$depToStatus;
        $interDepTags = array_intersect(array_keys($depToStatus), $depTags);
        $interStatus = [];
        foreach ($interDepTags as $v) {
            $interStatus = array_merge($depToStatus[$v], $interStatus);
        }
        $checkStatus = [];
        $types = [];
        if (!empty($depTag)) {
            if ($depTag[0] == 'XHSCB') {
                $checkStatus = [1, 2, 3, 4, 5, 6, 7];//市场部可见全部状态
                $types = [1, 2];
            } elseif ($depTag[0] == 'XHYYB') {
                $checkStatus = [2, 3, 4, 6, 7];//运营部可见
            } elseif ($depTag[0] == 'XHCWB') {
                $checkStatus = [3, 4, 7]; //财务可见
            }
        }
        $allStatus = array_values(array_unique(array_merge($checkStatus, $interStatus)));
        try {
            $condition = 'bDelete = 0';
            // 申请类型查询
            if ($type) {
                $condition .= " AND iType = $type";
            }
            // 审核状态查询
            if ($status) {
                $condition .= " AND iStatus = $status";
            }
            if (!empty($types)) {
                $types = implode(',', $types);
                $condition .= " and iType in(" . $types . ")";
            }
            // 关键字查询
            if ($key) {
                // 通过学校名称查询
                $schools = School::searchSchool($key);
                if (empty($schools)) {
                    //根据所属部门可查看的申请状态
                    $condition .= ' and sStudName like "%' . $key . '%"';
                    if ((Power::exist('School_SpecialApplyList_Check'))) {
                        $statusIds = $this->modelsManager->createBuilder()
                            ->columns("iId")
                            ->addFrom('Admin\Models\school\XhschoolApply')
                            ->where($condition)
                            ->inWhere('iStatus', $allStatus)
                            ->getQuery()
                            ->execute()
                            ->toArray();
                    } else {
                        $statusIds = [];
                    }
                    $statusIds = array_column($statusIds, 'iId');
                    $staffApplyIds = $this->modelsManager->createBuilder()
                        ->columns("iId")
                        ->addFrom('Admin\Models\school\XhschoolApply')
                        ->where($condition)
                        ->inWhere('iCreateUserId', $uids)
                        ->getQuery()
                        ->execute()
                        ->toArray();
                    $staffApplyIds = array_column($staffApplyIds, 'iId');

                    //扩展学校所属的申请
                    $schoolApplyIds = [];
                    if ($schoolIds !== true && !empty($schoolIds) && is_array($schoolIds)) {
                        $schoolApplyIds = $this->modelsManager->createBuilder()
                            ->columns("iId")
                            ->addFrom('Admin\Models\school\XhschoolApply')
                            ->where($condition)
                            ->inWhere('iSchoolId', $schoolIds)
                            ->getQuery()
                            ->execute()
                            ->toArray();
                        $schoolApplyIds = array_column($schoolApplyIds, 'iId');
                    } elseif ($schoolIds === true) {
                        $schoolApplyIds = $this->modelsManager->createBuilder()
                            ->columns("iId")
                            ->addFrom('Admin\Models\school\XhschoolApply')
                            ->where($condition)
                            ->getQuery()
                            ->execute()
                            ->toArray();
                        $schoolApplyIds = array_column($schoolApplyIds, 'iId');
                    }
                    $iIds = array_unique(array_merge($statusIds, $staffApplyIds, $schoolApplyIds));
                } else {
                    if ((Power::exist('School_SpecialApplyList_Check'))) {
                        $statusIds = $this->modelsManager->createBuilder()
                            ->columns("iId")
                            ->addFrom('Admin\Models\school\XhschoolApply')
                            ->where($condition)
                            ->inWhere('iStatus', $allStatus)
                            ->inWhere('iSchoolId', $schools)
                            ->getQuery()
                            ->execute()
                            ->toArray();
                    } else {
                        $statusIds = [];
                    }
                    //扩展部门所属的员工所创建的申请
                    $statusIds = array_column($statusIds, 'iId');
                    $staffApplyIds = $this->modelsManager->createBuilder()
                        ->columns("iId")
                        ->addFrom('Admin\Models\school\XhschoolApply')
                        ->where($condition)
                        ->inWhere('iCreateUserId', $uids)
                        ->inWhere('iSchoolId', $schools)
                        ->getQuery()
                        ->execute()
                        ->toArray();
                    $staffApplyIds = array_column($staffApplyIds, 'iId');
                    //扩展学校所属的申请
                    $schoolApplyIds = [];
                    if ($schoolIds !== true && !empty($schoolIds)) {
                        $schoolIds = array_intersect($schoolIds, $schools);
                        $schoolApplyIds = $this->modelsManager->createBuilder()
                            ->columns("iId")
                            ->addFrom('Admin\Models\school\XhschoolApply')
                            ->where($condition)
                            ->inWhere('iSchoolId', $schoolIds)
                            ->getQuery()
                            ->execute()
                            ->toArray();
                        $schoolApplyIds = array_column($schoolApplyIds, 'iId');
                    }
                    $iIds = array_unique(array_merge($statusIds, $staffApplyIds, $schoolApplyIds));
                }
            } else {
                //扩展部门及所在部门能审核或者审核过的申请(有申请权限)
                if ((Power::exist('School_SpecialApplyList_Check'))) {
                    $statusIds = $this->modelsManager->createBuilder()
                        ->columns("iId")
                        ->addFrom('Admin\Models\school\XhschoolApply')
                        ->where($condition)
                        ->inWhere('iStatus', $allStatus)
                        ->getQuery()
                        ->execute()
                        ->toArray();
                } else {
                    $statusIds = [];
                }
                $statusIds = array_column($statusIds, 'iId');

                //扩展部门员工创建的申请
                $staffApplyIds = $this->modelsManager->createBuilder()
                    ->columns("iId")
                    ->addFrom('Admin\Models\school\XhschoolApply')
                    ->where($condition)
                    ->inWhere('iCreateUserId', $uids)
                    ->getQuery()
                    ->execute()
                    ->toArray();
                $staffApplyIds = array_column($staffApplyIds, 'iId');

                //扩展学校所属的申请
                $schoolApplyIds = [];
                if ($schoolIds !== true && !empty($schoolIds) && is_array($schoolIds)) {
                    $schoolApplyIds = $this->modelsManager->createBuilder()
                        ->columns("iId")
                        ->addFrom('Admin\Models\school\XhschoolApply')
                        ->where($condition)
                        ->inWhere('iSchoolId', $schoolIds)
                        ->getQuery()
                        ->execute()
                        ->toArray();
                    $schoolApplyIds = array_column($schoolApplyIds, 'iId');
                } elseif ($schoolIds === true) {
                    $schoolApplyIds = $this->modelsManager->createBuilder()
                        ->columns("iId")
                        ->addFrom('Admin\Models\school\XhschoolApply')
                        ->where($condition)
                        ->getQuery()
                        ->execute()
                        ->toArray();
                    $schoolApplyIds = array_column($schoolApplyIds, 'iId');
                }
                $iIds = array_unique(array_merge($statusIds, $staffApplyIds, $schoolApplyIds));
            }

            $builder = $this->modelsManager->createBuilder()
                ->columns("iId,iSchoolId,iStudId,sStudName,iType,iTypeExpansion,sAttachmentUrl,iStatus,sRemarks,tCreateDate,tLastModifyDate,iCreateUserId,iPayState,sLeadPosition,sLeadName,sLeadPhone,sLeadCompany,sAccountNum,sIdentityNum")
                ->addFrom('Admin\Models\school\XhschoolApply')
                ->where($condition)
                ->inWhere('iId', $iIds)
                ->orderBy('iId desc');
            $data = Main::runBuilderPages($builder, true);
            // 数据展示类型切换
            foreach ($data['rows'] as $k => $row) {
                $data['rows'][$k]['iTypeName'] = self::$applyType[$row['iType']];
                $data['rows'][$k]['iPayStateName'] = self::$payState[$row['iPayState']];
//                $data['rows'][$k]['logonName'] = User::getLogonName($row['iStudId']);
                if ($row['iTypeExpansion']) {
                    $data['rows'][$k]['iTypeExpansion'] = self::$typeExpansion[$row['iType']][$row['iTypeExpansion']];
                }
                $data['rows'][$k]['iStatusText'] = $this->getApplyStatus($row['iStatus']);
                $data['rows'][$k]['sAttachmentUrl'] = json_decode($row['sAttachmentUrl'], true);
                $identityCode = XhsysUser::findFirst([
                    'columns' => 'sIdentityCode,sLogonName',
                    'conditions' => 'iUserId = ' . $row['iStudId'],
                ]);
                if ($identityCode) {
                    $data['rows'][$k]['sIdentityCode'] = $identityCode->sIdentityCode;
                    $data['rows'][$k]['logonName'] = $identityCode->sLogonName;
                }
            }
            Main::runUserNameById($data['rows'], ['iCreateUserId' => 'sCreateUserName'], true);
            Main::runSchoolNameByIdStr($data['rows'], ['iSchoolId' => 'sSchoolName']);
            return $this->sendJsonResponse($data);
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 获取申请状态的样式
     *
     * @param $status
     *
     * @return mixed
     *
     * create by zqk 20180927
     */
    private function getApplyStatus($status)
    {
        $final_Status = [
            1 => '<div class="grid-cell-text-bg-gray" style="display: inherit">待市场部审批</div>',
            2 => '<div class="grid-cell-text-bg-yellow" style="display: inherit">待运营部审批</div>',
            3 => '<div class="grid-cell-text-bg-blue" style="display: inherit">待财务部审批</div>',
            4 => '<div class="grid-cell-text-bg-green" style="display: inherit">审批通过</div>',
            5 => '<div class="grid-cell-text-bg-red" style="display: inherit">市场部审批不通过</div>',
            6 => '<div class="grid-cell-text-bg-red" style="display: inherit">运营部审批不通过</div>',
            7 => '<div class="grid-cell-text-bg-red" style="display: inherit">财务部审批不通过</div>',
        ];
        return $final_Status[$status];
    }

    /**
     * 新增表单
     *
     * @return View
     * @throws \Helpers\XhException
     * create by gby 20180705
     * modify by zqk 20180927
     * modify by zqk 20181024
     * modify by zqk 20181101
     */
    public function addStudentApplyAction()
    {
        if (!Power::exist('School_SpecialApplyList_Add')) {
            return $this->sendViewError('无特殊申请权限');
        }
        $iType = $this->request->getQuery('iType');
        $iId = $this->request->getQuery('iId');
        $applyInfo = [];
        $financeEdit = 0;
        $ifEdit = 0;
        if ($iId) {
            if (!Power::exist('School_SpecialApplyList_Edit')) {
                return $this->sendViewError('无特殊申请编辑权限');
            }
            $applyInfo = $this->getApplyInfoById($iId);
            if (!$applyInfo) {
                return $this->sendViewError('该申请不存在');
            }
            if ($applyInfo) {
                $ifEdit = 1;
                if ($applyInfo['iStatus'] == 4) {
                    $financeEdit = 1;
                }
            }
        }
        Assets::select2();
        Assets::easyUI('js/school_apply/addStudentApply.js');
        Assets::importMainJs('assets/jquery/jquery.form.js');
        $this->di->get('assets')
            ->addCss('assets/fileinput/fileinput.css')
            ->addJs('customer/js/fileinput.min.js')//修改过的
            ->addJs('customer/js/zh.js');
        $schoolIds = School::getPower();
        if (is_array($schoolIds)) {
            $schools = $this->modelsManager->createBuilder()
                ->columns('iSchoolId,sSchoolName')
                ->addFrom('Admin\Models\school\XhschoolInfo')
                ->where('bDelete = 0 and (iStatus = 1 OR iStatus = 2)')
                ->inWhere('iSchoolId', $schoolIds)
                ->getQuery()
                ->execute()
                ->toArray();
            $schoolList = array_column($schools, 'sSchoolName', 'iSchoolId');
        } elseif ($schoolIds) {
            $schoolList = School::getSchools();
        } else {
            $schoolList = [];
        }
        $bEstablished = $this->request->getQuery('bEstablished');
        $formButtonArr[] = ['id' => 'bt_form_add', 'text' => '提交'];
        $formButtonArr[] = ['id' => 'bt_form_close', 'text' => '取消'];
        $this->view->setVars([
            'SchoolList' => json_encode($schoolList),
            'iType' => $iType,
            'applyInfo' => $applyInfo,
            'ifEdit' => $ifEdit,
            'iId' => $iId,
            'financeEdit' => $financeEdit,
            'bEstablished' => $bEstablished,
            'typeExpansion' => self::$typeExpansion,
            'payState' => self::$payState,
            'FormButton' => Template::createButtonToolBar($formButtonArr),
        ]);
        return $this->view->pick('school_apply/addStudentApply');
    }

    /**
     * 根据选择的学校来获取学生名单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by gby 20180724
     */
    public function getStudentAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        $parameters = [
            'columns' => 'iUserId, sUserName, sLogonName',
            'conditions' => 'bDelete = 0 AND iUserType = 1 AND bDisable = 0 AND bHistory = 0'
        ];
        if ($schoolId) {
            $parameters['conditions'] .= " AND iSchoolId = :schoolId:";
            $parameters['bind'] = ['schoolId' => $schoolId];
        }
        try {
            $studentList = XhsysUser::find($parameters);
            $data = [];
            if ($studentList) {
                foreach ($studentList as $val) {
                    $data[$val['iUserId']] = $val['sUserName'] . '-' . $val['sLogonName'];
                }
            }
            return $this->sendJsonResponse($data);
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 根据学校Id获取联系人信息
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20181023
     */
    public function getContractBySchoolIdAction()
    {
        $schoolId = $this->request->getPost('schoolId');
        $schoolInfo = XhcustInfo::findFirst([
            'columns' => 'iCUId,iSchoolId',
            'conditions' => 'bDelete = 0 AND iSchoolId = :schoolId:',
            'bind' => ['schoolId' => $schoolId]
        ]);
        $data = [];
        if ($schoolInfo) {
            $iCUId = $schoolInfo->iCUId;
            $contacts = XhcustContact::find([
                'columns' => 'iCUCId,iUserId,sName',
                'conditions' => 'bDelete = 0 AND iCUId = ' . $iCUId,
            ])->toArray();
            foreach ($contacts as $contact) {
                if ($contact['iUserId']) {
                    $data[$contact['iUserId']] = $contact['sName'];
                } else {
                    $data[$contact['iCUCId']] = $contact['sName'];
                }

            }
        }
        return $this->sendJsonResponse($data);
    }

    /**
     * 上传图片
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by gby 20180822
     * modify by zqk 20181015
     */
    public function uploadImgAction()
    {
        set_time_limit(0);
        if (!$this->request->hasFiles()) {
            return $this->sendErrorResponse(400, '缺少文件');
        }
        $files = $this->request->getUploadedFiles();
        $urls = [];
        $types = [
            'image/jpeg',
            'image/png',
            'image/gif',
            'image/bpm',
        ];
        if (!empty($files)) {
            foreach ($files as $k => $file) {
                $filePath = Tool::buildPath(Main::getConfigByName('fileSave')['temp'], $file->getName());
                if ($file->getSize() > 5 * 1024 * 1024) {
//                    die(json_encode(['error' => '文件大小不可超过5M！']));
                    return $this->sendErrorResponse(500, '文件大小不可超过5M!');
                }
                $type = $file->getType();
                if (!in_array($type, $types)) {
                    return $this->sendErrorResponse(500, '文件非图片格式');
                };
                $file->moveTo($filePath);
                $url = Main::uploadToFileManageSystem($filePath);
                if (!$url) {
                    return $this->sendErrorResponse(500, '图片上传失败');
                }
                $urls[] = $url;
            }
        }
        return $this->sendJsonResponse($urls);
    }

    /**
     * 上传图片
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20181024
     */
    public function uploadFileAction()
    {
        if (!$this->request->hasFiles()) {
            return $this->sendErrorResponse(400, '缺少文件');
        }
        $file = $this->request->getUploadedFiles()[0];
        $type = $file->getType();
        $types = [
            'image/jpeg',
            'image/png',
            'image/gif',
            'image/bpm',
        ];
        if (!in_array($type, $types)) {
            return $this->sendErrorResponse(500, '文件非图片格式');
        };
        $filePath = Tool::buildPath(Main::getConfigByName('fileSave')['temp'], $file->getName());
        $fileName = $file->getName();
        $file->moveTo($filePath);
        $url = Main::uploadToFileManageSystem($filePath, 'img', null, true);
        if (!$url) {
            return $this->sendErrorResponse(500, '文件上传失败:没有文件url');
        } else {
            return $this->sendSuccessResponse(['url' => $url, 'fileName' => $fileName]);
        }
    }

    /**
     * 提交申请
     *
     * @return array|bool|mixed|null|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by gby 20180720
     * modify by zqk 20180930
     */
    public function saveStudentApplyAction()
    {
        if (!Power::exist('School_SpecialApplyList_Add')) {
            return $this->sendErrorResponse(403, '无特殊申请权限');
        }
        $data = $this->request->getPost();
        if ($data['iId']) {
            if (!Power::exist('School_SpecialApplyList_Edit')) {
                return $this->sendErrorResponse(403, '无特殊申请编辑权限');
            }
        }
        // 判断申请项是否存在
        if (!in_array($data['iType'], array_keys(self::$applyType))) {
            return $this->sendErrorResponse(400, '没有该项申请,请查证后再填写');
        }
        // 判断是否是申请教师子女或者贫困生，如果是，判断教师子女类型和贫困生等级是否正确
        if (in_array($data['iType'], [1, 2])) {
            $expansionType = self::$typeExpansion;
            if (!in_array($data['iTypeExpansion'], array_keys($expansionType[$data['iType']]))) {
                return $this->sendErrorResponse(400, '等级错误,请查证后再填写');
            }
        }
        // 判断学校是否为空
        if (!$data['iSchoolId'] && $data['iType'] != 8) {  //校外领导不需要学校
            return $this->sendErrorResponse(400, '请选择学校');
        }
        // 判断学生是否为空
        if (!$data['iStudId'] && !in_array($data['iType'], [8,9])) { //校外领导不需要选择学生
            return $this->sendErrorResponse(400, '请选择申请的学生');
        }

        //领导子女判断家长信息是否完整
        if ($data['iType'] == 6) {
            if (empty($data['sLeadName']) || empty($data['sLeadPosition']) || empty($data['sLeadPhone'])) {
                return $this->sendErrorResponse(400, '请填写完整领导信息');
            }
        }
        if ($data['iType'] == 8) {
            if (empty($data['sLeadCompany']) || empty($data['sLeadPosition']) || empty($data['sLeadPhone']) || empty($data['sStudName'])) {
                return $this->sendErrorResponse(400, '请完整填写领导信息');
            }
        }
        //新增学生
        if ($data['iType'] == 9) {
            if (empty($data['sIdentityNum'])) {
                return $this->sendErrorResponse(400, '请完整填写学生信息');
            }
            if ($data['sAccountNum']) {
                $userInfo = XhsysUser::findFirst([
                    'conditions' => 'bDelete = 0 AND sLogonName = "'.$data['sAccountNum'].'"',
                ]);
                if (!empty($userInfo)) {
                    if ($userInfo->sUserName != $data['sStudName'] || $userInfo->sIdentityCode != $data['sIdentityNum']) {
                        return $this->sendErrorResponse(400, '学生账号信息错误');
                    }
                }
            }
        }
        //平板租用
        if ($data['iType'] == 10) {
            XhsysUser::findFirst($data['iStudId'])->update(['iDevSource' => 2]);
        }
        // 判断申请证明是否填写 (只判断教师子女和贫困生的申请证明 以及领导申请)
        if (in_array($data['iType'], [1, 2, 5, 7])) {
            $msg = '';
            $error = '';
            foreach ($data['sAttachmentUrl'] as $key => $value) {
                switch ($key) {
                    case 'tch_img':
                        $msg = '教师证';
                        break;
                    case 'relation_img':
                        $msg = '出生证/户口本';
                        break;
                    case 'family_img':
                        $msg = '家庭贫困证明';
                        break;
                    case 'stud_img':
                        $msg = '学生贫困证明';
                        break;
                    case 'borrow_img':
                        $msg = '平板借用协议';
                        break;
//                    case 'finance_img':
//                        $msg = '财务附件';
//                        break;
                    case 'leader_img':
                        $msg = '学校领导证明';
                        break;
                    case 'grant_img':
                        $msg = '平板发放附件';
                        break;
                }
                if ($value == '') {
                    $error .= $msg . '不能为空<br/>';
                }
            }
            if ($error != '') {
                return $this->sendErrorResponse(400, rtrim($error, '<br/>'));
            }
            if (!$data['iId'] && !$data['bEstablished']) {
                $data['iStatus'] = 1;
            } elseif ($data['bEstablished']) {
                $data['iStatus'] = 4;
            }
        } elseif (!in_array($data['iType'], [1, 2, 5, 7, 9])) {
            if (!$data['iId'] && !$data['bEstablished']) {
                $data['iStatus'] = 2;
            } elseif ($data['bEstablished']) {
                $data['iStatus'] = 4;
            }
        } elseif ($data['iType'] == 9) {
            if (!$data['iId'] && !$data['bEstablished']) {
                $data['iStatus'] = 1;
            } elseif ($data['bEstablished']) {
                $data['iStatus'] = 4;
            }
        }
        try {
            // 数据处理
            if ($data['iType'] != 5 && $data['iType'] != 8 && $data['iType'] != 9) {
                $data['sStudName'] = substr($data['sStudName'], 0, strrpos($data['sStudName'], '-'));
            }
            if (!$data['iId']) {
                $condition = "bDelete = 0 AND iStudId = :studId: AND iType = :type: AND iStatus in({arr:array})";
            } else {
                $condition = "bDelete = 0 AND iId != " . $data['iId'] . " AND iStudId = :studId: AND iType = :type: AND iStatus in({arr:array})";
            }
            $parameters = [
                'columns' => 'iId,iStatus',
                'conditions' => $condition,
                'bind' => ['studId' => $data['iStudId'], 'type' => $data['iType'], 'arr' => [1, 2, 3, 4]]
            ];
            $applyList = XhschoolApply::findFirst($parameters);
            // 申请存在
            if ($applyList) {
                if (in_array($applyList->iStatus, [1, 2, 3, 10])) {
                    return $this->sendErrorResponse(400, '申请已经存在,请等待审批');
                } else {
                    return $this->sendErrorResponse(400, '不能重复申请');
                }
            }
            $this->db->begin();
            if ($data['iId']) {
                $obj = XhschoolApply::findFirst($data['iId']);
            } else {
                $obj = new XhschoolApply();
            }

            $data['sAttachmentUrl'] = json_encode($data['sAttachmentUrl']);
            $obj->assign($data);
            if (!$obj->save()) {
                $this->db->rollback();
                return $data['iId'] ? $this->sendErrorResponse(500, '编辑失败') : $this->sendErrorResponse(500, '创建失败');
            }
            $content = [];
            if (User::isAdmin()) {
                $content['userName'] = Main::getLoginUserInfo('logonName');
            } else {
                $content['userName'] = Main::getLoginUserInfo('userName');
            }
            if ($data['bEstablished']) {
                $content['title'] = '创建申请';
                $content['action'] = '添加已审核特殊申请';
            } elseif ($data['iId']) {
                $content['action'] = '编辑特殊申请';
                $content['title'] = '编辑申请';
            } else {
                $content['title'] = '创建申请';
                $content['action'] = '创建特殊申请';
            }

            $content['ifComment'] = 0;
            $sContent = json_encode($content);
            $applyLog = new XhschoolApplyLog();
            $applyLog->iApplyId = $obj->iId;
            $applyLog->sContent = $sContent;
            if (!$applyLog->save()) {
                $this->db->rollback();
                return $data['iId'] ? $this->sendErrorResponse(500, '编辑失败') : $this->sendErrorResponse(500, '创建失败');
            }
            $this->db->commit();
            return $data['iId'] ? $this->sendSuccessResponse('编辑成功') : $this->sendSuccessResponse('创建成功');
        } catch (Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 财务审核
     *
     *
     *
     * create by zqk 20181008
     */
    public function financeApprovalAction()
    {
        if (!Power::exist('School_SpecialApplyList_Check')) {
            return $this->sendViewError('没有审批权限');
        }
        Assets::easyUI('js/school_apply/financeApproval.js');
        $this->di->get('assets')
            ->addCss('assets/fileinput/fileinput.css')
            ->addJs('customer/js/fileinput.min.js')//修改过的
            ->addJs('customer/js/zh.js');
        $this->view->pick('school_apply/financeApproval');
    }

    /**
     * 审核申请
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180929
     */
    public function approvalApplyAction()
    {
        if (!Power::exist('School_SpecialApplyList_Check')) {
            return $this->sendErrorResponse(403, '没有审批权限');
        }
        $id = $this->request->getPost('id', 'int');
        if (!$id) {
            return $this->sendErrorResponse(400, '请选择要审批的申请');
        }
        $result = $this->request->getPost('result', 'int');
        if (!in_array($result, [0, 1])) {
            return $this->sendErrorResponse(400, '请选择正确的审批结果');
        }
        $comment = $this->request->getPost('comment');
        $depTags = Main::getLoginUserInfo('depTag');
        $userDepNames = Main::getLoginUserInfo('depName');
        $userDepName = !empty($userDepNames) ? $userDepNames[0] : '';
        $checkStatus = [];
        if (!empty($depTags)) {
            if ($depTags[0] == 'XHSCB') {
                $checkStatus = [1];//市场部可审核状态
            } elseif ($depTags[0] == 'XHYYB') {
                $checkStatus = [2];//运营部可审核状态
            } elseif ($depTags[0] == 'XHCWB') {
                $checkStatus = [3]; //财务可审核状态
            }
        }
        if (User::isAdmin()) {
            $checkStatus = [1, 2, 3];//管理员审核全部
        }
        try {
            $this->db->begin();
            $obj = XhschoolApply::findFirst($id);
            if ($obj) {
                // 判断当前记录是否已最终审核
                $status = $obj->iStatus;
                $type = $obj->iType;
                if (in_array($status, [4, 5, 6, 7])) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(400, '审批已完成');
                }
                $errorMsg = '';
                $newStatus = $status;
                $title = '';
                if ($status == 1) {
                    if ($type == 9) {
                        $accountNum = $obj->sAccountNum;
                        $userInfo = XhsysUser::findFirst([
                            'conditions' => 'bDelete = 0 AND sLogonName = "'.$accountNum.'"',
                        ]);
                        if (empty($userInfo)) {
                          return $this->sendErrorResponse(500, '该学生未创建账号');
                        }
                        if (empty($obj->iStudId)) {
                            $obj->iStudId = $userInfo->iUserId;
                        }
                    }
                    $errorMsg = '非市场部员工';
                    $title = '市场审批';
                    if ($result) {
                        $newStatus = 2;
                    } else {
                        $newStatus = 5;
                    }
                } elseif ($status == 2) {
                    $errorMsg = '非运营部员工';
                    $title = '运营审批';
                    if ($result) {
                        if ($obj->iType == 6 || $obj->iType == 8 || $obj->iType == 9) {
                            $newStatus = 4;
                        } else {
                            $newStatus = 3;
                        }
                    } else {
                        $newStatus = 6;
                    }
                } elseif ($status == 3) {
                    $errorMsg = '非财务部员工';
                    $title = '财务审批';
                    if ($result) {
                        $newStatus = 4;
                        $oldImgUrl = json_decode($obj->sAttachmentUrl, true);
                        $finaceImg = $this->request->getPost('sAttachmentUrl');
                        if (!empty($finaceImg) && !empty($oldImgUrl)) {
                            $picUrl = json_encode(array_merge($oldImgUrl, $finaceImg));
                            $obj->sAttachmentUrl = $picUrl;
                        } elseif (empty($oldImgUrl) && !empty($finaceImg)) {
                            $picUrl = json_encode($finaceImg);
                            $obj->sAttachmentUrl = $picUrl;
                        }
                    } else {
                        $newStatus = 7;
                    }
                }
                if (!in_array($status, $checkStatus)) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(400, $errorMsg);
                } else {
                    $obj->iStatus = $newStatus;
                    if (!$obj->save()) {
                        $this->db->rollback();
                        return $this->sendErrorResponse(400, '审批失败');
                    } else {
                        // 最终审核
                        if ($obj->iStatus == 4) {
                            $type = $obj->iType;
                            $studId = $obj->iStudId;
                            $re = 1;
                            switch ($type) {
                                case 1:
                                    // 修改教师子女属性
                                    $tchChildLevel = $obj->iTypeExpansion;
                                    $dDevCost = $obj->dDevCost;
                                    $dSerCost = $obj->dSerCost;
                                    // 获取收费教师子女的收费情况
                                    $re = Stud::setTchChild($studId, $tchChildLevel, $dDevCost, $dSerCost);
                                    break;
                                case 2:
                                    // 修改贫困生属性
                                    $iPoorLevel = $obj->iTypeExpansion;
                                    $re = Stud::setPoorLevel($studId, $iPoorLevel);
                                    break;
                            }
                            if (!$re) {
                                $this->db->rollback();
                                return $this->sendErrorResponse(400, '审批失败');
                            }
                        }
                        $content = [];
                        if (User::isAdmin()) {
                            $content['userName'] = Main::getLoginUserInfo('logonName');
                        } else {
                            $content['userName'] = $userDepName . '-' . Main::getLoginUserInfo('userName');
                        }
                        $content['action'] = $result ? '审批通过' : '审批驳回';
                        $content['comment'] = $comment;
                        $content['ifComment'] = 1;
                        $content['title'] = $title;
                        $sContent = json_encode($content);
                        $applyLog = new XhschoolApplyLog();
                        $applyLog->iApplyId = $obj->iId;
                        $applyLog->sContent = $sContent;
                        if (!$applyLog->save()) {
                            $this->db->rollback();
                            return $this->sendErrorResponse(400, '创建失败');
                        }
                        $this->db->commit();
                        return $this->sendSuccessResponse('审批成功');
                    }
                }
            } else {
                return $this->sendErrorResponse(400, '未找到该记录');
            }
        } catch (Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 删除
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     *
     * create by gby 20180720
     * modify by zqk 20180929
     */
    public function delApplyAction()
    {
        if (!Power::exist('School_SpecialApplyList_Del')) {
            return $this->sendErrorResponse(403, '无操作权限');
        }
        $id = $this->request->getPost('id', 'int');
        if (!$id) {
            return $this->sendErrorResponse(400, '请选择要删除的申请');
        }
        try {
            $this->db->begin();
            $apply = XhschoolApply::findFirst($id);
            if (!$apply) {
                $this->db->rollback();
                return $this->sendErrorResponse(400, '请选择要删除的项');
            }
            // 最终审核状态是否为通过
            if ($apply->iStatus == 4) {
                $res = 1;
                if ($apply->iType == 1) {
                    // 重置教师子女状态
                    $res = Stud::setTchChild($apply->iStudId, 1);
                } elseif ($apply->iType == 2) {
                    // 重置贫困生状态
                    $res = Stud::setPoorLevel($apply->iStudId, 0);
                }
                if (!$res) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(400, '删除失败');
                }
            }
            $apply->bDelete = 1;
            $re = $apply->save();
            if (!$re) {
                $this->db->rollback();
                return $this->sendErrorResponse(400, '删除失败');
            }
            //删除日志
            $content = [];
            if (User::isAdmin()) {
                $content['userName'] = Main::getLoginUserInfo('logonName');
            } else {
                $content['userName'] = Main::getLoginUserInfo('userName');
            }
            $sContent = json_encode($content);
            $content['action'] = '删除特殊申请';
            $content['ifComment'] = 0;
            $content['title'] = '删除';
            $applyLog = new XhschoolApplyLog();
            $applyLog->iApplyId = $id;
            $applyLog->sContent = $sContent;
            if (!$applyLog->save()) {
                $this->db->rollback();
                return $this->sendErrorResponse(400, '删除失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('删除成功');
        } catch (Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '删除失败', $e->getMessage());
        }
    }

    /**
     * 根据Id获取申请的相关日志
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180929
     */
    public function getApplyLogByIdAction()
    {
        $id = $this->request->getPost('id', 'int', 0);
        $logs = XhschoolApplyLog::find([
            'columns' => 'sContent,tCreateDate',
            'conditions' => 'bDelete = 0 And iApplyId = ' . $id
        ])->toArray();
        foreach ($logs as $k => $v) {
            $logs[$k]['sContent'] = json_decode($logs[$k]['sContent']);
        }
        return $this->sendJsonResponse($logs);
    }

    /**
     * 获取申请info
     *
     * @param int $iId
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by zqk 20181023
     * modify by zqk 20181024
     */
    public function getApplyInfoById($iId = 0)
    {
        if (empty($iId)) {
            return $this->sendErrorResponse('400', '参数错误');
        }
        $apply = XhschoolApply::findFirst([
            'conditions' => 'bDelete = 0 And iId = ' . $iId
        ]);
        if (!$apply) {
            return false;
        } else {
            $applyInfo = $apply->toArray();
            return $applyInfo;
        }
    }

    public function delFileAction()
    {
        return $this->sendSuccessResponse('success');
    }
}
